package com.yunhe.marketing.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.ReflectUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.es.util.QueryBuilderUtil;
import com.yunhe.marketing.client.AuthorityClient;
import com.yunhe.marketing.constant.EnterpriseConsts;
import com.yunhe.marketing.domain.Enterprise;
import com.yunhe.marketing.domain.FilterCondition;
import com.yunhe.marketing.esdomain.EsDataClueDemand;
import com.yunhe.marketing.esrepository.EsDataClueDemandrepository;
import com.yunhe.marketing.model.DemandFilterCondition;
import com.yunhe.marketing.model.DemandQueryCondition;
import com.yunhe.marketing.model.EnterpriseUpload;
import com.yunhe.marketing.model.EnterpriseUploadAQC;
import com.yunhe.marketing.repository.EnterpriseRepository;
import com.yunhe.marketing.repository.FilterConditionRepository;
import com.yunhe.marketing.service.IDemandRepositoryService;
import com.yunhe.marketing.service.SynchronizeDataService;
import com.yunhe.marketing.util.BeansUtil;
import com.yunhe.marketing.util.EnterpriseUtil;
import com.yunhe.common.util.CollectionUtil;
import com.yunhe.marketing.util.ExcelUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.*;

/**
 * @Author: DongWenYu
 * @Date: 2021/2/23 11:14
 */
@Service
public class DemandRepositoryServiceImpl implements IDemandRepositoryService {

    private static final Logger logger = LoggerFactory.getLogger(DemandRepositoryServiceImpl.class);

    private static final String infinite = "infinite";

    Map<String,Double> exchangeMap = new HashMap<>();

    @Autowired
    AuthorityClient authorityClient;

    @Autowired
    EnterpriseRepository enterpriseRepository;

    @Autowired
    FilterConditionRepository filterConditionRepository;

    @Autowired
    SynchronizeDataService synchronizeDataService;

    @Autowired
    EsDataClueDemandrepository esDataClueDemandrepository;

    @PostConstruct
    private void init(){
        exchangeMap.put("(美元)",6.5561);
        exchangeMap.put("(澳元)",4.9977);
        exchangeMap.put("(新加坡币)",4.8657);
        exchangeMap.put("(港币)",0.8435);
        exchangeMap.put("(欧元)",7.7237);
        exchangeMap.put("(元)",1.0);
    }
    @Override
    public List<Enterprise> upload(List<EnterpriseUpload> enterpriseUploadList,String channelSource) throws PinyinException {
        List<Enterprise> enterpriseList = new ArrayList<Enterprise>();
        List<Enterprise> updateList = new ArrayList<Enterprise>();
        List<Enterprise> allEnterpriseList = new ArrayList<Enterprise>();
        for (EnterpriseUpload enterpriseUpload : enterpriseUploadList){
            Enterprise enterpriseByLicense = enterpriseRepository.selectEnterpriseByLicense(enterpriseUpload.getLicense());
            Enterprise enterpriseByUpload = covertToEnterprise(enterpriseUpload,channelSource);
            if (enterpriseByLicense != null){
                if (!(EnterpriseConsts.INFORMATION_TYPE.Clue.value().equals(enterpriseByLicense.getInformationType()) &&
                        EnterpriseConsts.INFORMATION_TYPE.Clue.value().equals(enterpriseByUpload.getInformationType()))){
                    enterpriseByUpload.setInformationType(EnterpriseConsts.INFORMATION_TYPE.Demand.value());
                }
                enterpriseByUpload.setId(enterpriseByLicense.getId());
                updateList.add(enterpriseByUpload);
            }else {
                enterpriseList.add(enterpriseByUpload);
            }
        }
        if (!CollectionUtil.isEmpty(enterpriseList)){
            logger.info("{}条数据存储数据库",enterpriseList.size());

            enterpriseList.forEach(enterprise -> {
                int id = enterpriseRepository.insert(enterprise);
                enterprise.setId((long) id);
                allEnterpriseList.add(enterprise);

            });
//            int insertBatch = enterpriseRepository.insertBatch(enterpriseList);
            logger.info("{}条数据存储成功",enterpriseList.size());
        }
        if (!CollectionUtil.isEmpty(updateList)){
            logger.info("{}条数据更新数据库",updateList.size());
            int updateBatchById = enterpriseRepository.updateBatchById(updateList);
            logger.info("{}条数据更新成功",updateBatchById);

            allEnterpriseList.addAll(updateList);
        }

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>开始同步至es中>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        if (CollectionUtil.isNotEmpty(allEnterpriseList)) {
            logger.info("需要同步的列表不为空");
            List<EsDataClueDemand> esDataClueDemands = BeansUtil.listCopy(allEnterpriseList, EsDataClueDemand.class);
            synchronizeDataService.insertBatch(esDataClueDemands);
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>开始同步至es结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

        return enterpriseList;
    }

    @Override
    public List<Enterprise> uploadAQC(List<EnterpriseUploadAQC> enterpriseUploadAQCList) throws PinyinException {
        List<EnterpriseUpload> enterpriseUploadList = new ArrayList<>();
        for (EnterpriseUploadAQC enterpriseUploadAQC : enterpriseUploadAQCList){
            EnterpriseUpload enterpriseUpload = new EnterpriseUpload();
            BeanUtils.copyProperties(enterpriseUploadAQC,enterpriseUpload);
            enterpriseUploadList.add(enterpriseUpload);
        }

        return upload(enterpriseUploadList,EnterpriseConsts.CHANNEL_SOURCE.NetworkCrawling.value());
    }

    @Override
    public List<Enterprise> export(String idsString,  Long exportPeopleId, HttpServletResponse httpServletResponse) {
        List<Enterprise> updateData = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        if (!StringUtil.isEmpty(idsString)) {
            String[] split = idsString.split(",");
            for (String id : split) {
                ids.add(Long.parseLong(id));
            }
        }
        List<Enterprise> enterpriseList = enterpriseRepository.selectEnterpriseByIdBatch(ids);
        if (!CollectionUtil.isEmpty(enterpriseList)) {
            for (Enterprise enterprise : enterpriseList) {
                enterprise.setExportPeople(exportPeopleId);
                enterprise.setExportCount(enterprise.getExportCount() + 1);
                updateData.add(enterprise);
            }
        }
        if (!CollectionUtil.isEmpty(updateData)){
            enterpriseRepository.updateBatchById(updateData);
        }
        if (!CollectionUtil.isEmpty(enterpriseList)){
            ExcelUtils.export(enterpriseList, httpServletResponse, Enterprise.class);
        }
        return enterpriseList;
    }

    @Override
    public PageResult selectDemandByDemandQueryCondition(DemandFilterCondition demandFilterCondition , int page , int size) throws ParseException {
        /**
         * DemandFilterCondition转换为DemandQueryCondition
         * DemandFilterCondition区间为一个字段，起始值（下界）终止值（上界）用“，”隔开，如：500,1000
         * DemandQueryCondition区间为两个字段，xxxStart：500，xxxEnd：1000
         * 当DemandFilterCondition无终止值（上界）时（即筛选条件为大于等于某一值），终止值（上界）用infinite表示，如：500，infinite;此时DemandQueryCondition中xxxEnd的值为null
         * */
        DemandQueryCondition demandQueryCondition = new DemandQueryCondition();
        BeanUtils.copyProperties(demandFilterCondition,demandQueryCondition);

        String filterAreaRequirement = demandFilterCondition.getAreaRequirement();
        String filterFloorHeight = demandFilterCondition.getFloorHeight();
        String filterBearing = demandFilterCondition.getBearing();
        String filterElectricityConsumption = demandFilterCondition.getElectricityConsumption();

        String filterPaidInCapital = demandFilterCondition.getPaidInCapital();
        String filterEstablishDate = demandFilterCondition.getEstablishDate();
        String filterAnnualTurnover = demandFilterCondition.getAnnualTurnover();

        demandQueryCondition.setEnterpriseScaleSection(demandFilterCondition.getEnterpriseScale());
        demandQueryCondition.setRegisteredCapitalSection(demandFilterCondition.getRegisteredCapital());
        demandQueryCondition.setNumberOfInsuredSection(demandFilterCondition.getNumberOfInsured());

        if (filterAreaRequirement != null){
            String[] areaRequirement = filterAreaRequirement.split(",");
            if (areaRequirement.length ==2) {
                if(!StringUtil.isEmpty(areaRequirement[0])){
                    demandQueryCondition.setAreaRequirementStart(Double.valueOf(areaRequirement[0]));
                }
                if (infinite.equals(areaRequirement[1])) {
                    demandQueryCondition.setAreaRequirementEnd(null);
                } else {
                    demandQueryCondition.setAreaRequirementEnd(Double.valueOf(areaRequirement[1]));
                }
            }
        }
        if (filterFloorHeight != null){
            String[] floorHeight = filterFloorHeight.split(",");
            if (floorHeight.length ==2) {
                if(!StringUtil.isEmpty(floorHeight[0])){
                    demandQueryCondition.setFloorHeightStart(Integer.valueOf(floorHeight[0]));
                }
                if (infinite.equals(floorHeight[1])) {
                    demandQueryCondition.setFloorHeightEnd(null);
                } else {
                    demandQueryCondition.setFloorHeightEnd(Integer.valueOf(floorHeight[1]));
                }
            }
        }
        if (filterBearing != null){
            String[] bearing = filterBearing.split(",");
            if (bearing.length ==2) {
                if(!StringUtil.isEmpty(bearing[0])){
                    demandQueryCondition.setBearingStart(Double.valueOf(bearing[0]));
                }
                if (infinite.equals(bearing[1])) {
                    demandQueryCondition.setBearingEnd(null);
                } else {
                    demandQueryCondition.setBearingEnd(Double.valueOf(bearing[1]));
                }
            }
        }
        if (filterElectricityConsumption != null){
            String[] electricityConsumption = filterElectricityConsumption.split(",");
            if (electricityConsumption.length ==2) {
                if(!StringUtil.isEmpty(electricityConsumption[0])){
                    demandQueryCondition.setElectricityConsumptionStart(Double.valueOf(electricityConsumption[0]));
                }
                if (infinite.equals(electricityConsumption[1])) {
                    demandQueryCondition.setElectricityConsumptionEnd(null);
                } else {
                    demandQueryCondition.setElectricityConsumptionEnd(Double.valueOf(electricityConsumption[1]));
                }
            }
        }

        if (filterPaidInCapital != null){
            String[] paidInCapital = filterPaidInCapital.split(",");
            if (paidInCapital.length == 2) {
                if(!StringUtil.isEmpty(paidInCapital[0])){
                    demandQueryCondition.setPaidInCapitalStart(Double.valueOf(paidInCapital[0]));
                }
                if (infinite.equals(paidInCapital[1])) {
                    demandQueryCondition.setPaidInCapitalEnd(null);
                } else {
                    demandQueryCondition.setPaidInCapitalEnd(Double.valueOf(paidInCapital[1]));
                }
            }
        }
        if (filterAnnualTurnover != null){
            String[] annualTurnover = filterAnnualTurnover.split(",");
            if (annualTurnover.length == 2) {
                if(!StringUtil.isEmpty(annualTurnover[0])){
                    demandQueryCondition.setAnnualTurnoverStart(Double.valueOf(annualTurnover[0]));
                }
                if (infinite.equals(annualTurnover[1])) {
                    demandQueryCondition.setAnnualTurnoverEnd(null);
                } else {
                    demandQueryCondition.setAnnualTurnoverEnd(Double.valueOf(annualTurnover[1]));
                }
            }
        }
        if (filterEstablishDate != null){
            String[] establishDate = filterEstablishDate.split(",");
            if (establishDate.length == 2) {
                if(!StringUtil.isEmpty(establishDate[0])){
                    demandQueryCondition.setEstablishDateStart(establishDate[0]);
                }
                String establishDateEndStr = establishDate[1];
                if (infinite.equals(establishDateEndStr)) {
                    demandQueryCondition.setEstablishDateEnd(null);
                } else {
                    demandQueryCondition.setEstablishDateEnd(establishDateEndStr);
                }
            }
        }
        PageResult result = null;
        Pageable pageable = PageRequest.of(page -1 , size);
        //查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("informationType","2"));
        QueryBuilder queryBuilder = QueryBuilderUtil.getQueryBuilder(demandQueryCondition, boolQueryBuilder);
        //构建查询
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withSort(SortBuilders.fieldSort("allocationStatus.keyword").order(SortOrder.ASC).unmappedType("string"))
                .withSort(SortBuilders.fieldSort("operationStatus.keyword").order(SortOrder.ASC).unmappedType("string"))
                .withSort(SortBuilders.fieldSort("establishDateSort.keyword").order(SortOrder.ASC).unmappedType("long"))
                .withSort(SortBuilders.fieldSort("enterpriseNameInitials.keyword").order(SortOrder.ASC).unmappedType("string"))
                //.addAggregation(builder)
                .withPageable(pageable)
                .build();
        Page<EsDataClueDemand> esDataClueDemandPage = esDataClueDemandrepository.search(query);
        List<EsDataClueDemand> content = esDataClueDemandPage.getContent();
        List<Enterprise> enterpriseList = BeansUtil.listCopy(content, Enterprise.class);
        return new PageResult(page ,size, (int) esDataClueDemandPage.getTotalElements(),enterpriseList);
    }


    @Override
    public Enterprise selectDemandById(Long id) {
        return enterpriseRepository.selectDemandById(id);
    }

    @Override
    public FilterCondition selectFilterConditionByConditionId(Long id) {
        return filterConditionRepository.selectFilterConditionById(id);
    }


    @Override
    public FilterCondition saveDemandFilterCondition(Long userId , String conditionName , DemandFilterCondition demandFilterCondition) throws UniqueConstraintsException {
        FilterCondition filterCondition = new FilterCondition();
        filterCondition.setUserId(userId);
        filterCondition.setConditionName(conditionName);
        demandFilterCondition.setIndustryCategorySelct(null);
        filterCondition.setFilterCondition(JSONObject.toJSONString(demandFilterCondition));
        filterCondition.setConditionType(EnterpriseConsts.INFORMATION_TYPE.Demand.value());
        FilterCondition condition = filterConditionRepository.selectFilterConditionByConditionName(userId, conditionName);
        if (condition != null){
            throw new UniqueConstraintsException("名称为：" + conditionName + "的条件组已存在，请勿重复保存");
        }
        filterConditionRepository.insert(filterCondition);
        return filterCondition;
    }

    @Override
    public PageResult viewSavedFilterCondition(Long userId, int page, int size) {
        PageHelper.startPage(page,size);
        List<FilterCondition> filterConditions = filterConditionRepository.viewDemandSavedFilterCondition(userId);
        PageInfo<FilterCondition> pageInfo = new PageInfo<>(filterConditions);
        return new PageResult(page, size, (int) pageInfo.getTotal(), filterConditions);
    }

    @Override
    public PageResult selectFilterConditionByKeyName(Long userId, String keyName, int page, int size) {
        PageHelper.startPage(page,size);
        List<FilterCondition> filterConditions = filterConditionRepository.selectDemandFilterConditionByKeyName(userId, keyName);
        PageInfo<FilterCondition> pageInfo = new PageInfo<>(filterConditions);
        return new PageResult(page, size, (int) pageInfo.getTotal(), filterConditions);
    }

    @Override
    public int deleteById(Long id) {
        return filterConditionRepository.deleteById(id);
    }

    @Override
    public List<Enterprise> assign(String idsString, Long responsiblePersonId) throws ArgumentErrorException {
        List<Long> ids = new ArrayList<>();
        if (!StringUtil.isEmpty(idsString)) {
            String[] split = idsString.split(",");
            for (String s : split) {
                ids.add(Long.parseLong(s));
            }
        }
        List<Enterprise> enterpriseList = enterpriseRepository.selectEnterpriseByIdBatch(ids);
        List<Enterprise> updateList = new ArrayList<>();
        for (Enterprise enterprise : enterpriseList){
            if (EnterpriseUtil.canAllocated(enterprise)) {
                enterprise.setAllocationStatus(EnterpriseConsts.ALLOCATION_STATE.Allocated.value());
                enterprise.setAllocationDate(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date()));
                enterprise.setResponsiblePerson(responsiblePersonId);
                updateList.add(enterprise);
            }
        }
        if (!CollectionUtil.isEmpty(updateList)){
            enterpriseRepository.updateBatchById(updateList);

            List<EsDataClueDemand> esDataClueDemands = BeansUtil.listCopy(updateList, EsDataClueDemand.class);
            esDataClueDemandrepository.saveAll(esDataClueDemands);
        }
        return updateList;
    }

    private Enterprise covertToEnterprise(EnterpriseUpload enterpriseUpload,String channelSource) throws PinyinException {
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(enterpriseUpload, enterprise);
        if (enterprise.getContactNumber() == null) {
            enterprise.setContactNumber(enterpriseUpload.getOtherNumber());
        } else {
            if (!StringUtil.isEmpty(enterpriseUpload.getOtherNumber())) {
                enterprise.setContactNumber(enterprise.getContactNumber() + "," + enterpriseUpload.getOtherNumber());
            }
        }
        if (enterprise.getEmail() == null) {
            enterprise.setEmail(enterpriseUpload.getOtherEmail());
        } else {
            if (!StringUtil.isEmpty(enterpriseUpload.getOtherEmail())) {
                enterprise.setEmail(enterprise.getEmail() + "," + enterpriseUpload.getOtherEmail());
            }
        }
        if(EnterpriseConsts.CHANNEL_SOURCE.NetworkCrawling.value().equals(channelSource)){
            enterprise.setChannelSource(EnterpriseConsts.CHANNEL_SOURCE.NetworkCrawling.value());
            enterprise.setChannelSourceTitle(EnterpriseConsts.CHANNEL_SOURCE.NetworkCrawling.title());
            enterprise.setDetailChannelSource("爱企查Excel表格导入");
        }
        return autoWiredEnterpriseProperties(enterprise);
    }


    private Enterprise autoWiredEnterpriseProperties(Enterprise enterprise) throws PinyinException {
        String removeString = "万";
//        是否在园
        if (!StringUtil.isEmpty(enterprise.getLicense())) {
            if (Objects.requireNonNull(authorityClient.getByUnifiedSocialCreditCode(enterprise.getLicense()).getBody()).getResults() == null) {
                enterprise.setInPark("1");
            } else {
                enterprise.setInPark("2");
            }
        }

        //判断消息是需求还是线索
        if (EnterpriseConsts.INFORMATION_TYPE.Clue.value().equals(EnterpriseUtil.judgeInformationType(enterprise))){
            enterprise.setInformationType(EnterpriseConsts.INFORMATION_TYPE.Clue.value());
            enterprise.setInformationTypeTitle(EnterpriseConsts.INFORMATION_TYPE.Clue.title());
        }else {
            enterprise.setInformationType(EnterpriseConsts.INFORMATION_TYPE.Demand.value());
            enterprise.setInformationTypeTitle(EnterpriseConsts.INFORMATION_TYPE.Demand.title());
        }

        //企业名称缩写
        enterprise.setEnterpriseNameInitials(PinyinHelper.getShortPinyin(enterprise.getEnterpriseName()));

        if (StringUtil.isEmpty(enterprise.getChannelSource())) {
            //excel导入的渠道来源为自发导入
            enterprise.setChannelSourceTitle(EnterpriseConsts.CHANNEL_SOURCE.SpontaneousImport.title());
            enterprise.setChannelSource(EnterpriseConsts.CHANNEL_SOURCE.SpontaneousImport.value());
        }

        if (!StringUtil.isEmpty(enterprise.getRegisteredCapital())){
            enterprise.setRegisteredCapital(enterprise.getRegisteredCapital().replace(removeString,""));
            if (enterprise.getRegisteredCapital().contains(",")){
                enterprise.setRegisteredCapital(enterprise.getRegisteredCapital().replaceAll(",",""));
            }
            enterprise.setRegisteredCapital(convertExchange(enterprise.getRegisteredCapital()));
            if (StringUtil.isEmpty(enterprise.getRegisteredCapital())){
                enterprise.setRegisteredCapitalSection(null);
            } else {

                //具体值生成区间code
                double registeredCapital = Double.parseDouble(enterprise.getRegisteredCapital());
                if (registeredCapital < 100.00) {
                    enterprise.setRegisteredCapitalSection("1");
                }
                if (registeredCapital <= 500.00 && registeredCapital >= 100.00) {
                    enterprise.setRegisteredCapitalSection("2");
                }
                if (registeredCapital < 1000.00 && registeredCapital > 500.00) {
                    enterprise.setRegisteredCapitalSection("3");
                }
                if (registeredCapital >= 1000.00) {
                    enterprise.setRegisteredCapitalSection("4");
                }
            }
        }
        //导入金额去掉单位（万）存储，方便后续筛选排序
        if (!StringUtil.isEmpty(enterprise.getPaidInCapital())){
            enterprise.setPaidInCapital(enterprise.getPaidInCapital().replace(removeString,""));
        }
        if (!StringUtil.isEmpty(enterprise.getAnnualTurnover())){
            enterprise.setAnnualTurnover(enterprise.getAnnualTurnover().replace(removeString,""));
        }
        //参保人数具体值生成区间code
        if (!StringUtil.isEmpty(enterprise.getNumberOfInsured())){
            int numberOfInsured = Integer.parseInt(enterprise.getNumberOfInsured());
            if (numberOfInsured < 10){
                enterprise.setNumberOfInsuredSection("1");
            }
            if (numberOfInsured>=10 && numberOfInsured<20){
                enterprise.setNumberOfInsuredSection("2");
            }
            if (numberOfInsured>=20 && numberOfInsured<50){
                enterprise.setNumberOfInsuredSection("3");
            }
            if (numberOfInsured>=50 && numberOfInsured<100){
                enterprise.setNumberOfInsuredSection("4");
            }
            if (numberOfInsured>=100 && numberOfInsured<500){
                enterprise.setNumberOfInsuredSection("5");
            }
            if (numberOfInsured>=500){
                enterprise.setNumberOfInsuredSection("6");
            }
        }
        //公司规模具体值生成区间code
        if (!StringUtil.isEmpty(enterprise.getEnterpriseScale())){
            int enterpriseScale = Integer.parseInt(enterprise.getEnterpriseScale());
            if (enterpriseScale < 10){
                enterprise.setEnterpriseScaleSection("1");
            }
            if (enterpriseScale>=10 && enterpriseScale<20){
                enterprise.setEnterpriseScaleSection("2");
            }
            if (enterpriseScale>=20 && enterpriseScale<50){
                enterprise.setEnterpriseScaleSection("3");
            }
            if (enterpriseScale>=50 && enterpriseScale<100){
                enterprise.setEnterpriseScaleSection("4");
            }
            if (enterpriseScale>=100 && enterpriseScale<500){
                enterprise.setEnterpriseScaleSection("5");
            }
            if (enterpriseScale>=500){
                enterprise.setEnterpriseScaleSection("6");
            }
        }


        //意向区域拆分成省市区
        if (!StringUtil.isEmpty(enterprise.getIntentionArea())){
            String[] split = enterprise.getIntentionArea().split("-");
            //直辖市
            if (split.length == 2){
                enterprise.setIntentionProvinceTitle(split[0]);
                enterprise.setIntentionCityTitle(split[0]);
                enterprise.setIntentionDistrictTitle(split[2]);
            }
            if (split.length == 3){
                enterprise.setIntentionProvinceTitle(split[0]);
                enterprise.setIntentionCityTitle(split[1]);
                enterprise.setIntentionDistrictTitle(split[2]);
            }
        }

        //分配状态默认未分配
        enterprise.setAllocationStatus(EnterpriseConsts.ALLOCATION_STATE.Unallocated.value());
        enterprise.setAllocationStatusTitle(EnterpriseConsts.ALLOCATION_STATE.Unallocated.title());

        return enterprise;
    }

    private String convertExchange(String registeredCapital) {
        Iterator<Map.Entry<String, Double>> iterator = exchangeMap.entrySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next().getKey();
            if (registeredCapital.contains(key)){
                String replace = registeredCapital.replace(key, "");
               return String.valueOf(Double.parseDouble(replace)*exchangeMap.get(key));
            }
        }
        return null;
    }

}
